import {useState} from "react";
import {Image, Input, Text, View} from "@tarojs/components";
import Taro, {useLoad} from '@tarojs/taro'
import './index.scss'
import MapPin from "../../components/svg/map-pin2.svg";
import Users from "../../components/svg/users.svg";
import Calendar from "../../components/svg/calendar.svg";
import Eye from "../../components/svg/eye.svg";
import Image1 from "../../components/svg/image.svg";
import Image2 from "../../components/svg/image2.svg";
import Tag1 from "../../components/svg/tag.svg";
import Tag2 from "../../components/svg/tag2.svg";
import Comment1 from "../../components/svg/message-square.svg";
import Comment2 from "../../components/svg/message-square2.svg";
import File1 from "../../components/svg/file-text.svg";
import File2 from "../../components/svg/file-text2.svg";
import Trash2 from "../../components/svg/trash-2.svg";
import Download from "../../components/svg/download.svg";
import Video from "../../components/svg/video.svg";
import Send from "../../components/svg/send.svg";
import {postRequest, getRequest, deleteRequest} from '../../util/request'

export default function Index() {

  const [currTab, setCurrTab] = useState<string>('all');
  const [trainId, setTrainId] = useState('');
  const [commentContent, setCommentContent] = useState('');
  const [currType, setCurrType] = useState('全部');
  const [currTag, setCurrTag] = useState('全部');
  const [trainInfo, setTrainInfo] = useState<any>({});
  const [tags, setTags] = useState<string[]>(['全部']);
  const permission = Taro.getStorageSync('userPermission')
  const userId = Taro.getStorageSync('userId')


  useLoad((param) => {
    console.log('训练详情页加载', param)
    setTrainId(param.trainId)
    scanRecord(param.trainId)
    queryDetail(param.trainId)
  })

  const scanRecord = async (id) => {
    postRequest('/bsTrain/scan', {id: id ? id : trainId}, (res) => {
      console.log(res)
    })
  }

  const queryDetail = async (id) => {
    getRequest(`/bsTrain/${id ? id : trainId}`, (res) => {
      Taro.setNavigationBarTitle({title: res.data.title})
      setTrainInfo(res.data)
      setTags([...tags, ...res.data.allTags])
    })
  }

  const activeTab = (tab: string) => {
    setCurrTab(tab)
    setCurrType('全部')
    setCurrTag('全部')
  }

  const activeType = (type: string) => {
    setCurrType(type)
  }

  const activeTag = (tag: string) => {
    setCurrTag(tag)
  }

  const getActiveStyle = (tab: string) => {
    if (tab == currTab) {
      return {
        'borderBottom': '3px solid #3376F2', /* 底部边框 */
        'color': '#3376F2',
      }
    } else {
      return {}
    }
  }

  const getActiveStyle2 = (type: string) => {
    if (type == currType) {
      return {
        'backgroundColor': '#3376F2',
        'color': '#fff',
      }
    } else {
      return {}
    }
  }

  const getActiveStyle3 = (tag: string) => {
    if (tag == currTag) {
      return {
        'backgroundColor': '#3376F2',
        'color': '#fff',
      }
    } else {
      return {}
    }
  }

  const getActiveIcon = (tab: string, icon, icon2) => {
    if (tab == currTab) {
      return icon2
    } else {
      return icon
    }
  }

  const previewMedia = (media: any) => {
    if (media.fileType == 'video') {
      Taro.navigateTo({url: `/pages/video/index?url=${media.filePath}`});
    } else {
      Taro.previewImage({urls: [media.filePath]})
    }
  }

  const deleteComment = (id: any) => {
    Taro.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (res) {
        if (res.confirm) {
          deleteRequest(`/bsTrainComment/batch?ids=${id}`, (res1) => {
            if (res1.success) {
              Taro.showToast({title: '删除成功', icon: 'none'})
              queryDetail(null)
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }

  const downloadFile = (url: string) => {
    Taro.downloadFile({
      url, success: (res) => {
        console.log('downloadFile', res)
        if (res.statusCode == 200) {
          // Taro.getFileSystemManager().saveFile({
          //   tempFilePath: res.tempFilePath,
          // })
          Taro.openDocument({
            filePath: res.tempFilePath,
            showMenu: true
          })
        }
      }
    })

  }

  const sendComment = () => {
    const body = {
      trainId,
      content: commentContent
    }
    postRequest('/bsTrainComment/add', body, (res) => {
      if (res.success) {
        setCommentContent('')
        Taro.showToast({title: '评论成功', icon: 'none'})
        queryDetail(null)
      }
    })
  }

  return (
    <View className=''>
      <View className='top'>
        <View className='name'>{trainInfo.subTitle}</View>
        <View className='desc'>{trainInfo.description}</View>
        <View className='location'>
          <Image src={MapPin} className='avatar1' />{trainInfo.place}
        </View>
        <View className='persons'><Image src={Users} className='avatar1' />{trainInfo.participants}人参与</View>
        <View className='during-date'><Image src={Calendar}
          className='avatar1'
        />{trainInfo.startDate}~{trainInfo.endDate}</View>
        <View className='views'>
          <Image src={Eye} className='avatar1' />
          <Text className='count'>{trainInfo.views}</Text>
        </View>
      </View>
      <View className='tabBar'>
        <View className='tabBarItem' style={getActiveStyle('all')} onClick={() => {
          activeTab('all')
        }}
        >
          <Image src={getActiveIcon('all', Image1, Image2)} className='avatar2' />
          <Text className='tabTitle'>全部</Text>
        </View>
        <View className='tabBarItem' style={getActiveStyle('tag')} onClick={() => {
          activeTab('tag')
        }}
        >
          <Image src={getActiveIcon('tag', Tag1, Tag2)} className='avatar2' />
          <Text className='tabTitle'>标签</Text>
        </View>
        <View className='tabBarItem' style={getActiveStyle('comment')} onClick={() => {
          activeTab('comment')
        }}
        >
          <Image src={getActiveIcon('comment', Comment1, Comment2)} className='avatar2' />
          <Text className='tabTitle'>评论</Text>
        </View>
        <View className='tabBarItem' style={getActiveStyle('doc')} onClick={() => {
          activeTab('doc')
        }}
        >
          <Image src={getActiveIcon('doc', File1, File2)} className='avatar2' />
          <Text className='tabTitle'>资料</Text>
        </View>
      </View>
      <View className='content'>

        {currTab == 'all' && (
          <View className='media-type-view'>
            <View className='type-tag' style={getActiveStyle2('全部')} onClick={() => {
              activeType('全部')
            }}
            >全部</View>
            <View className='type-tag' style={getActiveStyle2('图片')} onClick={() => {
              activeType('图片')
            }}
            >图片</View>
            <View className='type-tag' style={getActiveStyle2('视频')} onClick={() => {
              activeType('视频')
            }}
            >视频</View>
          </View>
        )}

        {currTab == 'tag' &&
          (<View className='media-type-view'>
            {tags.filter(t => t !== '').map(tag => (
              <View className='type-tag' key={tag} style={getActiveStyle3(tag)} onClick={() => {
                activeTag(tag)
              }}
              >{tag}</View>
            ))}
          </View>)
        }

        {currTab == 'comment' &&
          trainInfo.comments.map(comment =>
            (
              <View className='comment-card' key={comment.id}>
                <Image src={comment.user?.avatarUrl} className='avatar3' />
                <View className='c-username'>{comment.user?.realname}</View>
                <View className='c-date'>{comment.crtTime}</View>
                <View className='c-content'>{comment.content}</View>
                {(userId == comment.personId || permission.includes('comment.manage')) && (
                  <Image src={Trash2} className='avatar2 delete-icon' onClick={() => {
                    deleteComment(comment.id)
                  }}
                  />)}
              </View>
            )
          )
        }
        {currTab == 'comment' &&
          (<View className='search-view'>
            <Input type='text' placeholder='写下你的评论...' className='search-input' value={commentContent}
              onInput={e => setCommentContent(e.detail.value)}
            />
            <View className='icon-view' onClick={() => {
              sendComment()
            }}
            >
              <Image src={Send} className='icon4' />
            </View>
          </View>)
        }
        {currTab == 'doc' &&
          trainInfo.documents.map(doc =>
            (
              <View className='doc-card' key={doc.id}>
                <Image src={File2} className='avatar3' />
                <View className='d-name'>{doc.name}</View>
                <View className='d-size'>{doc.docSize}</View>
                <Image src={Download} className='avatar2 download-icon' onClick={() => {
                  downloadFile(doc.url)
                }}
                />
              </View>
            )
          )
        }

        {(currTab == 'all') &&
          trainInfo.medias?.filter(media => currType == '全部' || (media.fileType == 'image' && currType == '图片') || (media.fileType == 'video' && currType == '视频')).map(media =>
            (
              <View className='media-card' key={media.id} onClick={() => {
                previewMedia(media)
              }}
              >
                <Image src={media.thumbnail} className='card-image' />
                {media.fileType == 'video' &&
                  <View className='video-icon'><Image src={Video} className='map-pin' /></View>}
                <View className='m-tagview'>
                  {media.tags?.split(',').filter(t => t !== '').map(tag => (<View key={tag} className='m-tags'
                    style={{top: media.fileType == 'video' ? '-196rpx' : '-110rpx'}}
                  >{tag}</View>))}
                </View>
              </View>
            )
          )
        }

        {(currTab == 'tag') &&
          trainInfo.medias?.filter(media => currTag == '全部' || media.tags.split(',').includes(currTag)).map(media =>
            (
              <View className='media-card' key={media.id} onClick={() => {
                previewMedia(media)
              }}
              >
                <Image src={media.thumbnail} className='card-image' />
                {media.fileType == 'video' &&
                  <View className='video-icon'><Image src={Video} className='map-pin' /></View>}
                <View className='m-tagview'>
                  {media.tags.split(',').map(tag => (<View key={tag} className='m-tags'
                    style={{top: media.fileType == 'video' ? '-196rpx' : '-110rpx'}}
                  >{tag}</View>))}
                </View>
              </View>
            )
          )
        }
      </View>
    </View>
  )
}
